import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/moudle/common_info.dart';
import 'package:sptapp/widget/common_widget.dart';

import '../../api/interface/user_api.dart';
import '../../api/request/response_data.dart';
import '../../basic/base_info.dart';
import '../../moudle/permiss_handler/permission_operate.dart';

class MinPeoductsPage extends StatefulWidget {
  const MinPeoductsPage({super.key});

  @override
  State<MinPeoductsPage> createState() => _MinPeoductsPageState();
}

class _MinPeoductsPageState extends State<MinPeoductsPage> {

  int selectIndex = 0;
  bool isEdit = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(baseDevices.isNotEmpty){
      for(var item in baseDevices){
        if(baseDeviceNum != null){
          if(item['sn'] == baseDeviceNum){
            selectIndex = baseDevices.indexOf(item);
          }
        }
      }
    }
  }

  _deleteDevice(item)async{
    Map<String,dynamic> data = {
      'id': item['id']
    };
    showLoading();
    ResponseData res = await UserAPI.deleteDevice(data);
    hideLoading();
    if(res.code == 200){
      selectIndex = 0;
      getDevicesList((){
        if(mounted){setState(() {
          if(baseDevices.isNotEmpty){
            for(var item in baseDevices){
              if(baseDeviceNum != null){
                if(item['sn'] == baseDeviceNum){
                  selectIndex = baseDevices.indexOf(item);
                }
              }
            }
            if(baseDevices[selectIndex]['sn'].toString() != baseDeviceNum){
              LocalBaseInfo.setDeviceNum(baseDevices[selectIndex]['sn']);
              baseDeviceNum = baseDevices[selectIndex]['sn'];
              baseDevice = baseDevices[selectIndex];
            }
          }else{
            Navigator.of(context).pop();
          }
        });}
      });
    }
    if(mounted){setState(() {});}
  }

  _showAddDeviceAlert(){
    SmartDialog.show(builder: (ctx){
      return Container(
        height: 530.w,
        padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
        decoration: BoxDecoration(
            color: Color(0xff1E1E1E),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
        ),
        child: Column(
          children: [
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Add new device',style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                  )
                ],
              ),
            ),
            SizedBox(height: 100.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                getCameraPermission(context, (){
                  Navigator.of(context).pushNamed('ScanPage').then((val){
                    if(mounted){setState(() {});}
                  });
                });
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Scan Your Device',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                Navigator.of(context).pushNamed('MinAddDeviceInput').then((val){
                  print('base===' + baseDevice.toString());
                  setState(() {});
                });
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xff2A2A2A),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Manual Entry'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
          ],
        ),
      );
    },alignment: Alignment.bottomCenter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, 'Product'.tr,actions: [
        GestureDetector(
          onTap: (){
            setState(() {
              isEdit = !isEdit;
              selectIndex = 0;
            });
          },
          child: Visibility(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 40.w),
              child: Text('Edit'.tr,style: TextStyle(
                  color: themeColor,
                  fontWeight: FontWeight.w600,
                  fontSize: 28.sp
              ),),
            ),
            visible: baseDevices.isNotEmpty,
          ),
        )
      ]),
      body: Column(
        children: [
          Expanded(
              child: SlidableAutoCloseBehavior(
                child: ListView.builder(itemBuilder: (ctx,index){
                  return Slidable(
                      key: Key(baseDevices[index]['sn']),
                      endActionPane: ActionPane(
                        motion: const ScrollMotion(),  // 滑动动画类型
                        extentRatio: 0.25,
                        children: [
                          // 删除按钮
                          SlidableAction(
                            onPressed: (context) {
                              _deleteDevice(baseDevices[index]);
                            },
                            backgroundColor: Colors.red,
                            foregroundColor: Colors.white,
                            label: 'Delete',
                          ),
                        ],
                      ),
                      child: GestureDetector(
                        onTap: (){
                          setState(() {
                            selectIndex = index;
                          });
                          // if(baseDeviceNum != baseDevices[selectIndex]['sn']){
                          //   LocalBaseInfo.setDeviceNum(baseDevices[selectIndex]['sn']);
                          //   baseDeviceNum = baseDevices[selectIndex]['sn'];
                          //   baseDevice = baseDevices[selectIndex];
                          // }
                          if(isEdit==false){
                            return;
                          }
                          Navigator.of(context).pushNamed('MinAddDeviceInput',arguments: baseDevices[index]).then((val){
                            print('base===' + baseDevice.toString());
                            setState(() {});
                          });
                        },
                        child: Container(
                          height: 210.w,
                          decoration: BoxDecoration(
                              color: isEdit && selectIndex == index? Colors.white.withOpacity(0.1):Colors.transparent
                          ),
                          padding: EdgeInsets.symmetric(horizontal: 40.w,),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Expanded(child: Container(
                                child: Row(
                                  children: [
                                    Expanded(child: Container(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Row(
                                            children: [
                                              Container(
                                                child: Text(baseDevices[index]['name']??'',style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 32.sp,
                                                    fontWeight: FontWeight.w600
                                                ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                                              ),
                                              SizedBox(width: 10.w,),
                                              Visibility(child: Image.asset('assets/common/product_edit.png',width: 48.w,),visible: isEdit,)
                                            ],
                                          ),
                                          SizedBox(height: 10.w,),
                                          Text(baseDevices[index]['type']??'unknown'.tr,style: TextStyle(
                                              color: Color.fromRGBO(255, 255, 255, 0.5),
                                              fontSize: 24.sp,
                                              fontWeight: FontWeight.w400
                                          ),),
                                          SizedBox(height: 10.w,),
                                          Text(baseDevices[index]['sn']??'',style: TextStyle(
                                              color: Color.fromRGBO(255, 255, 255, 0.5),
                                              fontSize: 24.sp,
                                              fontWeight: FontWeight.w400
                                          ),)
                                        ],
                                      ),
                                    )),
                                    Image.asset('assets/common/min_product_logo.png',width: 88.w,),
                                  ],
                                ),
                              )),
                              Container(
                                height: 1.w,
                                color: Colors.white.withOpacity(0.1),
                              )
                            ],
                          ),
                        ),
                      )
                  );
                },itemCount: baseDevices.length,padding: EdgeInsets.zero,),
              )
          ),
          SizedBox(height: 40.w,),
          Container(
            child: GestureDetector(
              onTap: (){
                _showAddDeviceAlert();
              },
              child: Container(
                width: 670.w,
                height: 108.w,
                decoration: BoxDecoration(
                  color: themeColor,
                  borderRadius: BorderRadius.circular(10.w)
                ),
                alignment: Alignment.center,
                child: Text('Add Product'.tr,style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w600
                ),),
              ),
            ),
          ),
          SizedBox(height: ScreenUtil().bottomBarHeight+20.w,)
        ],
      ),
    );
  }
}
